import { Request, Response } from 'express';
import { ApiResponseMeta, PaginationMeta, SuccessResponse, ErrorResponse } from '@/interfaces';
import { datetimeFormat, deepFormatDate } from '@utils/formatter';

export class ApiResponseBuilder {
  private readonly meta: ApiResponseMeta;
  constructor(req: Request, res: Response) {
    this.meta = this.fillResponseMeta(req, res);
  }
  // 成功
  success<T>(data?: T, message = '操作成功', pagination?: PaginationMeta): SuccessResponse<T> {
    return {
      code: 0,
      message,
      data: deepFormatDate(data) as T,
      ...(this.meta && { meta: this.meta }),
      ...(pagination && { pagination }),
    };
  }

  // 失败
  error(message: string = '服务器内部异常', code = 1, errors?: Record<string, any>): ErrorResponse {
    return {
      code,
      message,
      ...(errors && { errors }),
      ...(this.meta && { meta: this.meta }),
    };
  }

  // 带分页的成功
  paginate<T>(data: T[], total: number, pageNum: number, pageSize: number, message = 'OK'): SuccessResponse<T> {
    const totalPages = Math.ceil(total / pageSize);
    return this.success(deepFormatDate(data) as T, message, {
      pageNum,
      pageSize,
      total,
      totalPages,
    });
  }

  private fillResponseMeta(req: Request, res: Response): ApiResponseMeta {
    return {
      timestamp: datetimeFormat(new Date()),
      path: req.originalUrl || req.url,
      method: req.method,
      duration: res?.locals.startTime ? Date.now() - res.locals.startTime + 'ms' : undefined,
    };
  }
}
